import { ref } from 'vue';
import moment from 'moment';

export function useProTable(options) {
  const {
    apiFn, // 接口对象
    extParams = {}, // 固定的body入参
    extQuerys = {}, // 固定的url入参
    isClearReqEmptyField = true, // 提交给接口是否删除无效字段
    paramsHandler, // 最终提交给接口的参数劫持方法，用户修改最终提交的参数
    querysHandler, // 最终提交给接口的url参数劫持方法，用户修改最终提交的参数
    listHandler, // 改造表格数据
  } = options;
  const innerExtQuerys = extQuerys;
  let innerExtParams = extParams;
  const proTableRef = ref(null);
  const pagination = ref({
    background: true,
    page: 1,
    layout: 'total, sizes, prev, pager, next, jumper',
    pageSizes: [10, 20, 30, 40],
    size: 30,
    total: 0,
  });
  const filterTableData = ref({});
  async function remoteMethod({ searchData, filterData, pagination: page }) {
    let pageInfo = {};
    if (page) {
      pageInfo = {
        size: page.size, page: page.page,
      };
    }
    let querys = {
      ...pageInfo,
      ...innerExtQuerys,
      ...searchData,
      ...filterData,
    };
    let params = {
      ...searchData,
      ...filterData,
      ...innerExtParams,
      ...pageInfo,
    };
    if (isClearReqEmptyField) {
      Object.keys(params).forEach((k) => {
        if (!params[k] && params[k] !== 0) {
          delete params[k];
        }
      });
    }
    params = paramsHandler ? paramsHandler(params) : params;
    querys = querysHandler ? querysHandler(querys) : querys;
    const data = await apiFn(params, querys);
    let list = data?.records || data || [];
    pagination.value.total = data.total || list.length;
    // eslint-disable-next-line no-restricted-syntax,guard-for-in
    for (const i in list) {
      // eslint-disable-next-line no-restricted-syntax
      for (const j in list[i]) {
        if (j.includes('time') || j.includes('Time')) {
          if (list[i][j] && !list[i][j].toString().includes(':')) {
            list[i][j] = moment(list[i][j]).format('YYYY-MM-DD HH:mm:ss');
          }
        }
      }
    }
    if (listHandler) { list = listHandler(list); }
    return list;
  }
  const tableProps = {
    transformation: (val) => (val === undefined || val === '' || val === null ? '--' : val),
    yunPagination: true,
    // showTableSetting: true,
  };
  function reLoad(params) { // 刷新列表
    if (params) {
      innerExtParams = params;
    }
    proTableRef.value?.getData();
  }
  return {
    proTableRef,
    reLoad,
    pagination,
    remoteMethod,
    tableProps,
    filterTableData,
  };
}
